const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const User = require('./User');

// 定义系统日志模型
const SystemLog = sequelize.define('SystemLog', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: User,
      key: 'id'
    },
    onUpdate: 'CASCADE',
    onDelete: 'SET NULL'
  },
  action: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '操作类型: login, create, update, delete, etc.'
  },
  resourceType: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '资源类型: user, job, application, etc.'
  },
  resourceId: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '资源ID'
  },
  details: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '操作详情'
  },
  ipAddress: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '操作IP地址'
  }
}, {
  tableName: 'system_logs',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['user_id'] },
    { fields: ['action'] },
    { fields: ['resource_type', 'resource_id'] },
    { fields: ['created_at'] }
  ]
});

// 关联关系
SystemLog.belongsTo(User, { foreignKey: 'userId', as: 'user' });
User.hasMany(SystemLog, { foreignKey: 'userId', as: 'logs' });

module.exports = SystemLog;